package com.jiankangjin.trading.dao.utils;

import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class DbUtil {
	public static Connection getConnection() throws SQLException {
		Connection con = null;
		//sessionVariables=FOREIGN_KEY_CHECKS=0表示忽略外键关联
        try {
            Properties props = PropertiesLoaderUtils.loadAllProperties("jdbc.properties");
            con = DriverManager.getConnection(props.get("jdbc.url").toString(),
                    props.getProperty("jdbc.username"),
                    props.getProperty("jdbc.password"));
        } catch (IOException e) {
            e.printStackTrace();
        }
		return con;
	}

    public static String getUsername() {
        try {
            Properties props = PropertiesLoaderUtils.loadAllProperties("jdbc.properties");
            return props.getProperty("jdbc.username");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static void close(Connection con) {
		try {
			if(con!=null) con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void close(PreparedStatement ps) {
		try {
			if(ps!=null) ps.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void close(ResultSet rs) {
		try {
			if(rs!=null) rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
